﻿using System.Diagnostics;
using System.Runtime.InteropServices;
using SharpDX.DirectInput;
using TableTool.Model;
using TlToolBase;

namespace TableTool
{
    public partial class ElsTool : Form
    {
        int[] fuben63 = new int[] { 3, 4, 19, 7, 8, 11, 12, 15, 16, 19, 20, 23, 24, };
        int[] fuben94 = new int[] { 1, 2, 5, 6, 9, 10, 13, 14, 17, 18, 21, 22, };
        bool flag { get; set; }
        List<Key> downKeys = new List<Key>();
        /// <summary>
        /// 监视组件
        /// </summary>
        List<ucUserData> uclist = new List<ucUserData>();
        public static UserData usdata { get; set; }
        CEL占星 cel { get; set; }
        PRHelp prHelp { get; set; }
        /// <summary>
        /// 按键关闭
        /// </summary>
        KeyDownClose keyDownClose { get; set; }
        bool autoV { get; set; }
        DateTime autoVUptime { get; set; } = DateTime.Now;
        // 导入模拟键盘的方法
        [DllImport("user32.dll")]
        public static extern void keybd_event(Keys bVk, byte bScan, int dwFlags, int dwExtraInfo);
        public ElsTool()
        {
            InitializeComponent();
            this.Load += ElsTool_Load1;
            DoubleBuffered = true;
            this.FormClosing += ElsTool_FormClosing;
            flag = true;
            KeyLook();
            Task.Factory.StartNew(AutoDownKey);
        }
        private void ElsTool_Load1(object? sender, EventArgs e)
        {
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.Text = this.Text;
        }
        private void AutoDownKey()
        {
            while (flag)
            {
                if (autoV)
                {
                    keybd_event(Keys.V, 0x2F, 0, 0);
                    Thread.Sleep(100);
                    keybd_event(Keys.V, 0x2F, 2, 0);
                }
                Thread.Sleep(1000);
            }
        }



        private void KeyLook()
        {
            var directInput = new DirectInput();
            var Devices = directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices);
            foreach (var item in Devices)
            {
                if (item.Type == DeviceType.Keyboard)
                {
                    var mykey = new SharpDX.DirectInput.Keyboard(directInput);
                    mykey.Acquire();
                    Task.Factory.StartNew(() =>
                    {
                        int flagindex = 0;
                        while (flag)
                        {
                            KeyboardState kstate = mykey.GetCurrentState();
                            if (kstate != null)
                            {
                                string value = "";
                                foreach (var item in kstate.PressedKeys)
                                {
                                    if (downKeys.Count > 0)
                                    {
                                        if (downKeys[downKeys.Count - 1] != item)
                                        {
                                            downKeys.Add(item);
                                        }
                                    }
                                    else
                                    {
                                        downKeys.Add(item);
                                    }
                                    if (item == Key.NumberPad1)
                                    {
                                        if (cel != null)
                                        {
                                            cel.reFlag = true;
                                        }
                                    }
                                    if (item == Key.F7)
                                    {
                                        this.Invoke(new Action(() => { toolStripLabel4_Click(null, null); }));
                                    }
                                    if (prHelp != null)
                                    {
                                        prHelp.KeyInput(item);
                                    }
                                }
                                try
                                {
                                    string downkeys = "";
                                    foreach (var item1 in downKeys)
                                    {
                                        downkeys += item1.ToString() + " ";

                                    }
                                    SetLable(label14, downkeys);
                                    uclist.ForEach(uc =>
                                    {
                                        var ex = uc.To0(downkeys);
                                        if (ex)
                                        {
                                            downKeys.Clear();
                                        }
                                    });

                                }
                                catch (Exception ex)
                                {
                                    SetLable(label14, ex.Message);
                                }
                                if (downKeys.Count > 4)
                                {
                                    downKeys.RemoveAt(0);
                                }
                            }
                            flagindex++;
                            groupBox3.Invoke(() =>
                            {
                                groupBox3.Text = "按键" + flagindex;
                            });
                            if (flagindex > 100)
                            {
                                flagindex = 0;
                            }
                            Thread.Sleep(50);
                        }
                    });
                }
            }
        }
        private void ElsTool_FormClosing(object? sender, FormClosingEventArgs e)
        {
            flag = false;
            timer1.Stop();
            FileDataClass.Save<UserData>(usdata);
        }

        private void SetLable(Label lb, string value)
        {
            if (lb.InvokeRequired)
            {
                lb.Invoke(new Action<Label, string>(SetLable), lb, value);
            }
            else
            {
                lb.Text = value;
            }
        }
        private void ElsTool_Load(object sender, EventArgs e)
        {
            usdata = FileDataClass.Get<UserData>();
            iniLookItem();
            tbEdBiLi.Text = usdata.edBiLi.ToString();
            timer1.Start();
        }

        private void iniLookItem()
        {
            flowLayoutPanel1.Controls.Clear();
            foreach (var item in uclist)
            {
                item.Close();
            }
            uclist.Clear();
            foreach (var item in usdata.dataItems)
            {
                ucUserData uc = new ucUserData();
                uc.userDataItem = item;
                uc.Width = flowLayoutPanel1.Width - 1;
                flowLayoutPanel1.Controls.Add(uc);
                uclist.Add(uc);
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (fuben63.Contains(DateTime.Now.Hour))
            {
                label1.Text = "当前开门63";
            }
            else
            {
                label1.Text = "当前开门94";
            }
            uclist.ForEach(uc => uc.Ex());
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            rbRmb.TextChanged -= textBox3_TextChanged;
            if (double.TryParse(tbEdBiLi.Text, out double bili))
            {
                if (double.TryParse(tbED.Text, out double ed))
                {
                    var dst = ed / 1 * bili;
                    SetBili(rbRmb, dst);
                }
            }
            rbRmb.TextChanged += textBox3_TextChanged;
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            tbED.TextChanged -= textBox2_TextChanged;
            if (double.TryParse(tbEdBiLi.Text, out double bili))
            {
                if (double.TryParse(rbRmb.Text, out double rmb))
                {
                    var dst = rmb / bili * 1;
                    SetBili(tbED, dst);
                }
            }
            tbED.TextChanged += textBox2_TextChanged;
        }

        private void SetBili(TextBox textBox, double value)
        {
            textBox.Text = value.ToString();
        }


        /// <summary>
        /// 监听管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            LookModelEdit lookModelEdit = new LookModelEdit();
            lookModelEdit.FromColse += LookModelEdit_FromColse;
            lookModelEdit.Show();
        }

        private void LookModelEdit_FromColse()
        {
            iniLookItem();
        }

        private void tbEdBiLi_TextChanged(object sender, EventArgs e)
        {
            double.TryParse(tbEdBiLi.Text, out double bili);
            usdata.edBiLi = bili;
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            if (cel != null)
            {
                cel.Close();
                cel = null;
            }
            if (cel == null)
            {
                cel = new CEL占星();
            }
            cel.Show();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", "https://gitee.com/rwhaoo/als-light-tool.git");
        }

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            toolStripLabel4.Enabled = false;
            if (DateTime.Now - autoVUptime > TimeSpan.FromSeconds(1))
            {
                autoV = !autoV;
                if (autoV)
                {
                    toolStripLabel4.BackColor = Color.Green;
                    toolStripLabel4.ForeColor = Color.Green;
                }
                else
                {
                    toolStripLabel4.BackColor = Color.Gray;
                    toolStripLabel4.ForeColor = Color.Gray;
                }
                autoVUptime = DateTime.Now;
            }
            toolStripLabel4.Enabled = true;
        }

        private void toolStripLabel5_Click(object sender, EventArgs e)
        {
            if (prHelp != null)
            {
                prHelp.Close();
                prHelp = null;
            }
            prHelp = new PRHelp();
            prHelp.Show();
        }

        private void toolStripLabel6_Click(object sender, EventArgs e)
        {
            if (keyDownClose != null)
            {
                keyDownClose.Close();
            }
            keyDownClose = new KeyDownClose();
            keyDownClose.Show();
        }

        private void toolStripLabel7_Click(object sender, EventArgs e)
        {
            ElsTool.usdata.cel_x = 0;
            ElsTool.usdata.cel_y = 0;
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }

        }
    }
}
